package com.ipzoe.common.captcha.repository;

import com.ipzoe.common.captcha.CaptchaCode;
import com.ipzoe.common.captcha.CaptchaCodeRepository;
import com.ipzoe.common.captcha.config.CaptchaCodeProperties;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;

/**
 * Redis验证码存储器，存储在redis中
 * 
 * @author Eric
 * @date 2019/12/02
 */
@Slf4j
public class RedisCaptchaCodeRepository implements CaptchaCodeRepository {

    @Setter
    private RedisTemplate<String, Object> redisTemplate;
    
    @Setter
    private CaptchaCodeProperties captchaCodeProperties;

    @Override
    public void save(String key, CaptchaCode code) {
        // 验证码剩余的有效期
        long expireSecond = LocalDateTime.now().until(code.getExpireTime(), ChronoUnit.SECONDS);
        if (expireSecond > 0) {
            redisTemplate.opsForValue().set(captchaCodeProperties.getCodeKeyPrefix() + key, code, expireSecond,
                TimeUnit.SECONDS);
        }
        log.debug("验证码存取的Redis实现类 保存的键为 {},值为 {}", key, code);
    }

    @Override
    public CaptchaCode get(String key) {
        CaptchaCode code =
            (CaptchaCode)redisTemplate.opsForValue().get(captchaCodeProperties.getCodeKeyPrefix() + key);
        log.debug("验证码存取的Redis实现类 获取的键为 {},值为{} ", key, code);
        return code;
    }

    @Override
    public void remove(String key) {
        redisTemplate.delete(captchaCodeProperties.getCodeKeyPrefix() + key);
    }

}
